package com.sharp.join.tk.mybatis.framework.join;

import com.sharp.join.tk.mybatis.utils.ReflectionUtil;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.Config;
import tk.mybatis.mapper.entity.EntityTable;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.resolve.EntityResolve;

import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Title: JoinEntityHelper
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/7/4 18:24
 */
@Slf4j
public class JoinEntityHelper extends EntityHelper {


    private static final EntityResolve DEFAULT = new JoinEntityResolve();

    /**
     * 实体类解析器
     */
    private static EntityResolve resolve = DEFAULT;

    /**
     * 初始化实体属性
     *
     * @param entityClass
     * @param config
     */
    public static synchronized void initEntityNameMap(Class<?> entityClass, Config config) {
        if (getEntityTableMap().get(entityClass) != null) {
            return;
        }
        //创建并缓存EntityTable
        EntityTable entityTable = resolve.resolveEntity(entityClass, config);
        getEntityTableMap().put(entityClass, entityTable);
    }

    @SuppressWarnings("unchecked")
    public static Map<Class<?>, EntityTable> getEntityTableMap() {
        Field field = ReflectionUtil.getField(EntityHelper.class, "entityTableMap");
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        try {
            return (Map<Class<?>, EntityTable>) field.get(ReflectionUtil.newInstance(EntityHelper.class));
        } catch (IllegalAccessException e) {
            log.error("", e);
            throw new MapperException("getEntityTableMap failed", e);
        }
    }

    public static String getTableName(Class<?> entityClass) {
        if (entityClass == null) {
            return null;
        }
        if (entityClass.isAnnotationPresent(Table.class)) {
            return entityClass.getAnnotation(Table.class).name();
        } else {
            return getTableName(entityClass.getSuperclass());
        }
    }
}
